#-*- coding: utf-8 -*-

# subversion info:
# $HeadURL: https://htpc-utils.googlecode.com/svn/trunk/HtpcUtils/SubDaemon.py $
# $Author: SkAsI.7 $
# $Id: SubDaemon.py 8 2010-02-24 16:21:18Z SkAsI.7 $
# $Revision: 8 $

"""
Subtitle daemon module. Provides automatic subtitle download and management.
"""

# Imports externals
import socket
import logging
import datetime
import PyRSS2Gen

# Imports internals
import Database


class EventManager(object):
  """
  EventManager class. Provides operations for event management.
  """

  def __init__(self, filename, link=None):
    object.__init__(self)
    self.__log = logging.getLogger('htpc-event')
    self.__filename = filename
    self.__link = link

  def add(self, title, description):
    """
    Add a new event to the event list.

    :param title: Event's title.
    :type title: str

    :param description: Event's description.
    :type subLanguage: str

    :raises: RuntimeError if something go bad.
    """
    Database.Event(title=title, description=description)
    self._update()

  def delete(self, title):
    """
    Delete a event from the event list.

    :param title: Event's title beginnging. Every event starting with this
      string will be deleted.
    :type title: str

    :raises: RuntimeError if something go bad.
    """
    for event in Database.Event.select():
      if event.title.startswith(title):
        event.destroySelf()
    self._update()

  def eventList(self):
    """
    Returns the events in the event list.

    :returns: the list of events.
    :rtype: dict list
    """
    events = []
    for event in Database.Event.select(orderBy=Database.Event.q.date).reversed():
      events.append("""
Title: %s
Description: %s
Added datetime: %s""" % (event.title
  , event.description
  , event.date.strftime('%d/%m/%y %H:%M:%S')))
    return events

  def _update(self):
    """
    Update RSS based on new events.
    """
    items = []
    for event in list(Database.Event.select(
        orderBy=Database.Event.q.date).reversed()[:30]):
      items.append(
        PyRSS2Gen.RSSItem(
          title=event.title,
          description=event.description,
          pubDate=event.date
        )
      )

    rss = PyRSS2Gen.RSS2(
      title='htpc-utils feed on %s' % socket.gethostname(),
      link=self.__link or 'http://code.google.com/p/htpc-utils/',
      description='htpc-event automagically generated RSS feed',
      lastBuildDate=datetime.datetime.now(),
      items=items
    )
    try:
      rss.write_xml(open(self.__filename, 'w'))
    except IOError, msg:
      self.__log.error('Unable to write RSS feed: %s' % msg)

